/*!
 * Ext JS Library 3.3.1
 * Copyright(c) 2006-2010 Sencha Inc.
 * licensing@sencha.com
 * http://www.sencha.com/license
 */
ReferenceWindow = Ext.extend(Ext.app.Module, {
	id : 'ref-win',
	autostart : true,
	store : null,
	baseUri: null,
	init : function() {
		this.launcher = {
			text : 'References Window',
			iconCls : 'refwin-icon',
			handler : this.createWindow,
			scope : this
		};
	},

	reloadReferences : function(baseUri) {
		if (baseUri!=null)
			this.baseUri = baseUri;
		if (this.store!=null){
		// change the store's url
			this.store.reload();
			this.store.proxy.conn.url = this.store.url + '&baseUri=' + this.baseUri;
			this.store.reload({callback: function(){
					Ext.ComponentMgr.get('mydesktop').getModule('ref-win').filter();
				
			}});
			}
		
		
		
	},
	/*
	 * This function filters the data of the reference store. There are
	 * three possibilities to filter: - Only the rate - Only the content
	 * like username, tag,... - content and rate
	 * 
	 */

	 filter : function() {
		// Value of the searchField
		var searchValue = Ext.getCmp("searchField").getValue();
		
		var rateValue = Ext.getCmp("ratingCombo").getValue();
		var fieldFilter = Ext.getCmp("fieldFilter").getValue();
		
		// first case: the searchfield is empty, so we only have to filter
		// the rate
		// or,if the rate is not set, the filter will be cleared
		if (searchValue == "") {
			// Look if the rate filter is set
			if (parseInt(rateValue)==rateValue) {
				this.store.filter([ {
					fn : function(record) {
							return record.get('avgRating') >= rateValue;
					}
				} ]);
			}else
				this.store.clearFilter()

		} else {
			// case two and three: filter the searchfield content
			this.store.filter([ {
				property : fieldFilter,
				value : searchValue,
				anyMatch : true, // optional, defaults to true
				caseSensitive : false
			// optional, defaults to true
			}, {
				fn : function(record) {
					// Look if the rate filter is set
					if (parseInt(rateValue)==rateValue)						
						return record.get('avgRating') >= rateValue;
					else
						return record;
				}
			} ]);
		}

	},
	createWindow : function() {
		var desktop = this.app.getDesktop();
		var win = desktop.getWindow('ref-win');

		// create the data store
		var store = new Ext.data.JsonStore({
			autoDestroy : true,
			totalProperty : 'results',
			root : 'rows',
			url : './references?action=getReferences',
			fields : [ 'id', 'ownerId', 'ownerUsername', 'myRating',
					'avgRating', 'tags', 'targetRefType', 'targetUri',
					'targetXpath', 'semanticRelation' ]
		});

		this.store = store;
		/*
		 * Create a Combobox for a rating filter
		 */
		// ComboBox creation
		var combo = new Ext.form.ComboBox({
			store : new Ext.data.ArrayStore({
				autoDestroy : true,
				fields : [ 'rating' ],
				data : [ ['-1'],['0'],[ '1' ], [ '2' ], [ '3' ], [ '4' ], [ '5' ] ]
			}),
			listeners : {
				"select" : function(field, event) {
					Ext.ComponentMgr.get('mydesktop').getModule('ref-win').filter();
				}
			},
			id: 'ratingCombo',
			displayField : 'rating',
			valueField : 'rating',
			width: 50,
			mode : 'local',
			emptyText : 'Rating',
			selectOnFocus : true,
			mode : 'local',
			triggerAction : 'all',
			typeAhead : true
		});
		/*
		 * Create a Combobox for a rating filter
		 */
		// ComboBox creation
		var fieldFilter = new Ext.form.ComboBox({
			store : new Ext.data.ArrayStore({
				autoDestroy : true,
				fields : [ 'filter' ],
				data : [ [ 'ownerUsername' ], [ 'tags' ],
							[ 'targetRefType' ], [ 'targetUri' ] , ['semanticRelation']]
			}),
			listeners : {
				"select" : function(field, event) {
					Ext.ComponentMgr.get('mydesktop').getModule('ref-win').filter();
				}
			},
			displayField : 'filter',
			width: 100,
			id: 'fieldFilter',
			valueField : 'filter',
			mode : 'local',
			value: 'ownerUsername',
			selectOnFocus : true,
			mode : 'local',
			triggerAction : 'all',
			typeAhead : true
		});
		
		var textField = new Ext.form.TextField({
				name : 'searchField',
				width: 100,
				id : 'searchField',
				emptyText : 'enter search term',
				enableKeyEvents : true,
				listeners : {
					"keydown" : function(field, event) {
						if (event.getKey() == 13) {
							Ext.ComponentMgr.get('mydesktop').getModule('ref-win').filter();
						}
					}
				}
			
		});

		// create the Grid - EditorGridPanel
		var grid = new Ext.grid.GridPanel({
			store : store,
			columns : [ /*{
				id : 'id',
				header : 'ID',
				width : 20,
				sortable : true,
				dataIndex : 'id'
			}, {
				id : 'ownerId',
				header : 'Owner-ID',
				width : 70,
				sortable : true,
				dataIndex : 'ownerId'
			}, */{
				id : 'ownerUsername',
				header : 'Owner',
				width : 100,
				sortable : true,
				dataIndex : 'ownerUsername'
			}, {
				id : 'myRating',
				header : 'myRating',
				width : 20,
				sortable : true,
				dataIndex : 'myRating'
			}, {
				id : 'avgRating',
				header : 'AvgRating',
				width : 20,
				sortable : true,
				dataIndex : 'avgRating'
			}, {
				id : 'tags',
				header : 'tags',
				width : 120,
				sortable : true,
				dataIndex : 'tags'/*,
				editor: new Ext.form.TextField({
					
	                allowBlank: false
	            })*/
			}, {
				id : 'targetRefType',
				header : 'targetRefType',
				width : 120,
				sortable : true,
				dataIndex : 'targetRefType'
			}, {
				id : 'targetUri',
				header : 'targetUri',
				width : 120,
				sortable : true,
				dataIndex : 'targetUri'
			}, {
				id : 'targetXpath',
				header : 'targetXpath',
				width : 120,
				sortable : true,
				dataIndex : 'targetXpath'
			}, {
				id : 'semanticRelation',
				header : 'Semantik',
				width : 120,
				sortable : true,
				dataIndex : 'semanticRelation'
			} ],
			// inline toolbars
			tbar : [
			/*
			 * { html: '<div id="rating1">' +'<input type="radio"
			 * name="rating1" value="0.5" title="Very poor">' +'<input
			 * type="radio" name="rating1" value="1" title="Very poor">' +'<input
			 * type="radio" name="rating1" value="1.5" title="Not that bad">' +'<input
			 * type="radio" name="rating1" value="2" title="Not that bad">' +'<input
			 * type="radio" name="rating1" value="2.5" title="Average">' +'<input
			 * type="radio" name="rating1" value="3" title="Average">' +'<input
			 * type="radio" name="rating1" value="3.5" title="Good">' +'<input
			 * type="radio" name="rating1" value="4" title="Good">' +'<input
			 * type="radio" name="rating1" value="4.5" title="Perfect">' +'<input
			 * type="radio" name="rating1" value="5" title="Perfect">' +'</div>'
			 *  },
			 */
			fieldFilter,
			textField, {
				text : 'Search',
				tooltip : 'Click hier to filter your Resources',
				iconCls : 'search',
				handler : Ext.ComponentMgr.get('mydesktop').getModule('ref-win').filter()
			}, '-', combo ],

			/*
			 * listeners: { cellclick: function(grid, rowIndex, colIndex) { if
			 * (colIndex > 0) { var rec = grid.store.getAt(rowIndex); //Opens
			 * the clicked Website in a new BrowserWindow
			 * MyDesktop.getModule('browser-win').createWindow(rec.get('targetUri'),
			 * rec.get('targetUri'), rec.get('targetXpath')); } } },
			 */
			stripeRows : true,
			title : 'References',
			// config options for stateful behavior
			stateful : true,
			stateId : 'grid'
		});

	

		// left mouseclick opens the website in a browser-window
		grid.addListener('rowclick', function(grid, rowIndex, e) {
			e.stopEvent();
			grid.getSelectionModel().selectRow(rowIndex);
			var record = grid.getStore().getAt(rowIndex);
			// Opens the clicked Website in a new BrowserWindow
			MyDesktop.getModule('browser-win').createWindow(
					record.get('targetUri'), record.get('targetUri'),
					record.get('targetXpath'));
		});

		// context menu for rating and stuff.
		grid.addListener('rowcontextmenu', function(grid, rowIndex, e) {
			e.stopEvent();
			grid.getSelectionModel().selectRow(rowIndex);
			var row = grid.getStore().getAt(rowIndex);
			var coords = e.getXY();
			var url = row.data.targetUri;

			// RATING
			var items = new Array();
			items.push({
				text : 'Rate 0',
				handler : function() {
					ReferenceManager.setRating(url, 0, function(success) {
						store.reload();
						var baseUri = Ext.ComponentMgr.get('mydesktop').getModule('ref-win').baseUri;
						Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(baseUri);						
					});
				}
			});
			items.push({
				text : 'Rate 1',
				handler : function() {
					ReferenceManager.setRating(url, 1, function(success) {
						store.reload();
						var baseUri = Ext.ComponentMgr.get('mydesktop').getModule('ref-win').baseUri;
						Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(baseUri);
					});
				}
			});
			items.push({
				text : 'Rate 2',
				handler : function() {
					ReferenceManager.setRating(url, 2, function(success) {
						store.reload();
						var baseUri = Ext.ComponentMgr.get('mydesktop').getModule('ref-win').baseUri;
						Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(baseUri);
					});
				}
			});
			items.push({
				text : 'Rate 3',
				handler : function() {
					ReferenceManager.setRating(url, 3, function(success) {
						store.reload();
						var baseUri = Ext.ComponentMgr.get('mydesktop').getModule('ref-win').baseUri;
						Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(baseUri);
					});
				}
			});
			items.push({
				text : 'Rate 4',
				handler : function() {
					ReferenceManager.setRating(url, 4, function(success) {
						store.reload();
						var baseUri = Ext.ComponentMgr.get('mydesktop').getModule('ref-win').baseUri;
						Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(baseUri);
					});
				}
			});
			items.push({
				text : 'Rate 5',
				handler : function() {
					ReferenceManager.setRating(url, 5, function(success) {
						store.reload();
						var baseUri = Ext.ComponentMgr.get('mydesktop').getModule('ref-win').baseUri;
						Ext.ComponentMgr.get('mydesktop').getModule('ref-win').reloadReferences(baseUri);
					});
				}
			});

			var menu = new Ext.menu.Menu({
				items : [
						{
							text : 'Rate this reference',
							menu : {
								items : items
							}
						},
						{
							text : 'Share this reference',
							handler : function() {
								MyDesktop.getModule('shareref-win')
										.createWindow(row.data.id);
							}
						},
						{
		                	text: 'Add a note',
		                	handler: function(){
		                		var uri = row.data.id;
		                		MyDesktop.getModule('addnote-win').createWindow(uri);
		                	}
	                	},{
		                	text: 'Show notes',
		                	handler: function(){
		                		var uri = row.data.id;
		                		MyDesktop.getModule('notesviewer-win').createWindow(uri);
	                		}
	                	},{
	                		text: 'Add semantic context',
	                		handler: function(){
	                			MyDesktop.getModule('addsemanticrelation-win').createWindow(row.data.id);
	                		}
	                	}]
			});
			menu.showAt([ coords[0], coords[1], coords[2], coords[3] ]);
		});

		store.load();

		if (!win) {
			win = desktop.createWindow({
				id : 'ref-win',
				title : 'Reference Window',
				width : 400,
				height : 300,
				x : 700,
				y : 5,
				iconCls : 'refwin-icon',
				shim : false,
				animCollapse : false,
				border : false,
				constrainHeader : true,
				collapsible : true,
				layout : 'fit',
				items : [ grid ]
			});
		}
		win.show();

	}

});
